package com.yanxu;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025-05-29-2025
 * @Description: server 服务端
 */
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;
        try {
            //启动 ServerSocket，监听 8888 端口
            serverSocket = new ServerSocket(9999);
            //serverSocket.bind(new InetSocketAddress("127.0.0.1", 9999));
            while (true) {
                // accept 等待客户端连接
                // accept 是阻塞函数，会一直在这里等待有客户端上线连接它!!!
                // 直到有客户端连接过来，才会继续往下走
                Socket socket = serverSocket.accept();
                String clientName = socket.getRemoteSocketAddress() + ":" + socket.getPort();
                System.out.println(clientName + " 上线了!!!");

                // 获取 reader、writer
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

                // 读取客户端发送的消息
                String msg = reader.readLine();
                System.out.println(clientName + ": " + msg);

                // 回写客户端消息
                writer.write("服务端：" + msg + "\n");
                writer.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            serverSocket.close();
        }
    }
}